"""Performance record model for employee reward tracking."""

from __future__ import annotations

from datetime import date
from typing import TYPE_CHECKING

from sqlalchemy import Date, ForeignKey, Integer, Numeric, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from ..models.base import TimestampMixin

if TYPE_CHECKING:
    from ..models.user import User


class PerformanceRecord(Base, TimestampMixin):
    """Daily performance record for employee reward calculation.

    Tracks 4 key metrics:
    - deals_count: Number of closed deals
    - showings_count: Number of property showings with customers
    - new_customers_count: Number of new customers acquired
    - followup_visits_count: Number of customer follow-up visits

    Daily reward calculation:
    daily_reward = MIN(deals×10 + showings×5 + new_customers×5 + followups×5, 100)
    """

    __tablename__ = "performance_records"
    __table_args__ = (UniqueConstraint("user_id", "record_date", name="uq_user_date"),)

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    user_id: Mapped[int] = mapped_column(
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    record_date: Mapped[date] = mapped_column(Date, nullable=False, index=True)

    # Four key metrics
    deals_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of closed deals"
    )
    showings_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of property showings"
    )
    new_customers_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of new customers acquired"
    )
    followup_visits_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of customer follow-up visits"
    )

    # Calculated reward (max 100 per day)
    daily_reward: Mapped[float] = mapped_column(
        Numeric(10, 2), nullable=False, default=0.0, comment="Daily reward amount (max 100)"
    )

    # Relationships
    user: Mapped["User"] = relationship("User", back_populates="performance_records")

    @staticmethod
    def calculate_reward(deals: int, showings: int, new_customers: int, followups: int) -> float:
        """Calculate daily reward based on activity counts.

        Formula: MIN(deals×10 + showings×5 + new_customers×5 + followups×5, 100)

        Args:
            deals: Number of closed deals
            showings: Number of property showings
            new_customers: Number of new customers
            followups: Number of follow-up visits

        Returns:
            Daily reward amount (0-100)
        """
        base_reward = deals * 10 + showings * 5 + new_customers * 5 + followups * 5
        return min(base_reward, 100.0)
